'use strict';

const Service = require('egg').Service;
const JWT = require('jsonwebtoken');
const uuidv4 = require('uuid').v4;
const moment = require('moment');
class UserService extends Service {

  // 注册
  async signup(data) {
    const res = {};
    const queryResult = await this.app.mysql.get('user', {
      name: data.name,
    });
    if (queryResult) {
      res.code = -1;
      res.msg = '用户已存在';
    } else {
      const uId = uuidv4();
      data.id = uId;
      const result = await this.app.mysql.insert('user', data);
      res.data = result;
      res.code = 0;
      res.msg = '注册成功';
    }
    return res;
  }
  // 登录
  async signin(data) {
    // const { ctx } = this;
    const res = {};
    const queryResult = await this.app.mysql.get('user', {
      name: data.name,
    });
    if (!queryResult) {
      res.code = -1;
      res.msg = '用户不存在，请注册';
      res.data = {};
    } else {
      const result = await this.app.mysql.get('user', data);
      if (!result) {
        res.code = -1;
        res.msg = '密码错误，请重新输入';
        res.data = {};
      } else {
        const token = JWT.sign({
          id: result.id,
        }, this.config.keys, {
        });
        result.token = token;
        res.data = result;
        res.code = 0;
        res.msg = '登录成功';
      }
    }
    return res;
  }

  // 获取用户信息
  async getUserInfo(data) {
    const res = {};
    // 根据token解析出userid
    const uIdData = JWT.verify(data.token, this.config.keys);
    const result = await this.app.mysql.select('user', {
      where: { id: uIdData.id },
      columns: [ 'id', 'name', 'phone', 'email', 'role', 'avatar', 'createTime', 'lastLoginTime', 'lastLoginPlace' ],
    });
    if (result) {
      res.data = result[0];
      res.code = 0;
      res.msg = '获取用户信息成功';

    } else {
      res.code = -1;
      res.msg = '获取用户信息失败';
    }
    return res;
  }
  // 获取用户列表
  async getUserListByName(name) {
    const userList = await this.app.mysql.query(`select id,name,phone,email,role,avatar,createTime,lastLoginTime,lastLoginPlace from user where name like '%${name}%'`);
    userList.forEach(item => {
      item.createTime = item.createTime ? moment(item.createTime).format('YYYY-MM-DD HH:mm:ss') : '';
      item.lastLoginTime = item.lastLoginTime ? moment(item.lastLoginTime).format('YYYY-MM-DD HH:mm:ss') : '';
    });
    return userList;
  }
  // 通过用户id获取用户信息
  async getUserInfoById(id) {
    const res = {};
    // 根据token解析出userid
    const result = await this.app.mysql.select('user', {
      where: { id },
      columns: [ 'id', 'name', 'phone', 'email', 'role', 'avatar' ],
    });
    if (result) {
      res.data = result[0];
      res.code = 0;
      res.msg = '获取用户信息成功';

    } else {
      res.code = -1;
      res.msg = '获取用户信息失败';
    }
    return res;
  }

  async updateUser(data) {

    const result = await this.app.mysql.update('user', data);

    console.log('result:', result);
    if (result.affectedRows === 1) {
      return {
        code: 0,
      };
    }
    return {
      code: -1,
    };
  }
  async resetPasswordById(id, password) {
    const result = await this.app.mysql.query(`update user set password = '${password}' where id = '${id}'`);
    if (result.affectedRows === 1) {
      return {
        code: 0,
      };
    }
    return {
      code: -1,
    };
  }
  //
  async deleteUserById(id) {
    const result = await this.app.mysql.delete('user', { id });
    if (result.affectedRows === 1) {
      return {
        code: 0,
      };
    }
    return {
      code: -1,
    };
  }

  async getRoleList() {
    const result = await this.app.mysql.select('role', {
      where: {
        is_delete: 0,
      },
    });
    return result;
  }

}

module.exports = UserService;
